package com.example.nutritionmanager.ocr

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import com.example.nutritionmanager.R
import dagger.hilt.android.AndroidEntryPoint
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

@AndroidEntryPoint
class CameraActivity : AppCompatActivity() {

    private lateinit var imageView: ImageView
    private lateinit var captureButton: Button
    private lateinit var previewView: PreviewView
    private lateinit var cameraExecutor: ExecutorService

    private val captureImageRequestCode = 1001

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)
        // 获取 Toolbar 并设置
        val toolbar: Toolbar = findViewById(R.id.toolbarCamera)
        setSupportActionBar(toolbar)

        // 设置返回按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white)

        // 处理返回按钮的点击事件
        toolbar.setNavigationOnClickListener {
            onBackPressed()  // 返回上一个页面
        }

        imageView = findViewById(R.id.imageView)
        captureButton = findViewById(R.id.captureButton)
        previewView = findViewById(R.id.previewView)  // 获取 PreviewView 用于显示实时预览

        cameraExecutor = Executors.newSingleThreadExecutor()

        captureButton.setOnClickListener {
            scan()
        }

        // 启动相机预览
        startCamera()
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

        cameraProviderFuture.addListener({
            // 使用 CameraProvider 绑定相机生命周期
            val cameraProvider = cameraProviderFuture.get()

            val preview = Preview.Builder()
                .build()

            preview.setSurfaceProvider(previewView.surfaceProvider)  // 设置预览视图

            val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK) // 选择后置摄像头
                .build()

            try {
                cameraProvider.unbindAll() // 解绑所有已绑定的用例
                cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview
                )
            } catch (e: Exception) {
                Toast.makeText(this, "相机初始化失败", Toast.LENGTH_SHORT).show()
            }

        }, ContextCompat.getMainExecutor(this))
    }

    private fun scan() {
//        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//        if (intent.resolveActivity(packageManager) != null) {
//            // 创建一个文件 URI 保存照片
//            val photoUri: Uri = createImageUri()  // 你可以创建方法来生成 URI
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
//            startActivityForResult(intent, captureImageRequestCode)
//        }
        val intent = Intent(this, OCRResultActivity::class.java)
        startActivity(intent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == captureImageRequestCode && resultCode == RESULT_OK) {
            val photoUri: Uri? = data?.data
            if (photoUri != null) {
                // 显示捕获的图像
                imageView.setImageURI(photoUri)

                // 跳转到显示图像的活动
                val intent = Intent(this, DisplayImageActivity::class.java)
                intent.putExtra("imageUri", photoUri.toString())
                startActivity(intent)
            }
        }
    }

    private fun createImageUri(): Uri {
        // 创建用于保存照片的 URI
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "captured_image.jpg")
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraApp")
        }
        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        return uri ?: throw IllegalArgumentException("无法创建图片 URI")
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraExecutor.shutdown()  // 关闭执行器
    }
}
